import Taro from '@tarojs/taro'
import { baseURL, WxSource } from './constants'

const getRequest = (url, data) => Taro.request({
	url: baseURL(url),
	data,
	method: 'GET'
}).then(res => {
	return res
}).catch(err => {
	console.log('get请求错误error=', err)
})

const postRequest = (url, data) => Taro.request({
	url: baseURL(url),
	data: JSON.stringify(data),
	method: 'POST',
	// mode: 'nocors'
}).then(res => {

	return res 
}).catch(err => {
	console.log('post请求错误error=', err)
})

const requestInterceptor = (chain) => {
	const requestParams = chain.requestParams
	// const { method, data, url } = requestParams
	const token = Taro.getStorageSync('sla_air_place_token')
	let header = {
		...requestParams.header,
		'Content-Type': 'application/json;charset=UTF-8;',
		source: WxSource,
		auth: '2019-10-11 12:22:11',
		sigParam: '2019-10-11 12:22:11',
	}
	if(token){
		header.token = token
	}
	requestParams.header = header
  return chain.proceed(requestParams)
		.then(checkStatus)
		.then(res => {
			// TODO: token过期，重新登录处理
			return res
    }).catch(err => {
			console.log('请求error==', err)
		})
} 

function checkStatus(response){
	if(!response) {
		return 
	}
	if(response.statusCode >= 200 && response.statusCode <= 304){
		return response.data
	}
	const error = new Error('网络请求失败');

  error.response = response;

  return Promise.reject(error);
}

Taro.addInterceptor(requestInterceptor)

export default {
	getRequest,
	postRequest
}